<?php
class Topic extends CI_Model
{
	function __construct()
	{
		parent::__construct();
	}
	function get_topics($cat_id,$last=0)
	{
		$this->db->select('*');
		if($last!=0)
		{
			$this->db->order_by('update_date','desc');
			$query = $this->db->get_where('topics',array('cid'	=>$cat_id),$last);
			return $query;
		}
		
		$query = $this->db->get_where('topics',array('cid'=>$cat_id));
		return $query;
	}
	function get_content($id)
	{
		$this->db->select('*');
		$query= $this->db->get_where('topics',array('id'	=>$id));
		return $query->row_array();
	}
	function create($data)
	{
		$valid=$this->valid($data);
		if($valid!='ok') return array('content'	=> $valid,
										'type'	=> 'error');
		$this->db->insert('topics',$data);
		return array('content'	=> 'Topic was created successful!',
						'type'	=> 'success');
	}
	function update($data)
	{
		$valid=$this->valid($data);
		if($valid!='ok') return array('content'	=> $valid,
										'type'	=> 'error');
		$this->db->update('topics',$data,array('id'	=> $data['id']));
		return array('content'	=> 'Topic was updated successful!',
						'type'	=> 'success');
	}
	function delete($id)
	{
		$this->db->delete('topics',array('id'	=> $id));
		return array('content'=>'topic_del_success',
		'type'=>'info');
	}
	function valid($data)
	{
		$this->db->select('*');
		if(isset($data['cid']) &&$data['cid']!=0){
			$query=$this->db->get_where('categories',array('id'	=>$data['cid']));
			if($query->num_rows==0) return 'Invalid category!';
		}
		if($data['title']=='') return 'Topic\' title is too short!';
		if($data['content']=='') return 'Content can not be blank!';
		return 'ok';
	}
}
?>